import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.FileReader;
import java.io.IOException;
import java.util.List;

public class ActionFactory implements IFactory<IAction> {

  @Override
  public IAction build(String path) {
    var action = new Action();
    try {
      FileReader reader = new FileReader(path);
      var parser = new JSONParser();
      var jsonObj = (JSONObject) parser.parse(reader);
      var actions = (JSONArray) jsonObj.get("actions");

      for (var obj : actions) {
        var o = (JSONObject) obj;
        var triggers = (List<String>) o.get("triggers");
        var subjects = (List<String>) o.get("subjects");
        var consumed = (List<String>) o.get("consumed");
        var produced = (List<String>) o.get("produced");
        var narration = (String) o.get("narration");
        var item = new ActionItem();
        item.setConsumed(consumed);
        item.setTriggers(triggers);
        item.setSubjects(subjects);
        item.setNarration(narration);
        item.setProduced(produced);
        action.getActions().add(item);
      }
    } catch (IOException | ParseException e) {
      throw new RuntimeException(e);
    }
    return action;
  }
}
